package com.xxxx.controller;

import com.xxxx.AdminUtils;
import com.xxxx.pojo.Admin;
import com.xxxx.pojo.R;
import com.xxxx.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Map;
import java.util.UUID;

/**
 * @author achao
 * @version 1.0
 */

@RestController
public class AdminInfoController {

    @Autowired
    private AdminService adminService;

    @Value("${fileUrl}")
    private String baseUrl;

    @Value("${server.port}")
    private String serverPort;

    @ApiOperation(value = "更新当前用户信息")
    @PutMapping("/admin/info")
    public R updateAdmin(@RequestBody Admin admin, Authentication authentication) {
        if (adminService.updateById(admin)) {
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,
                    null, authentication.getAuthorities()));
            return R.success("更新成功！");
        }
        return R.error("更新失败!");
    }

    @ApiOperation(value = "更新用户密码")
    @PutMapping("/admin/pass")
    public R updateAdminPassword(@RequestBody Map<String, Object> info) {
        String ordPass = (String) info.get("ordPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updateAdminPassword(ordPass, pass, adminId);
    }

    @ApiOperation(value = "上传用户头像")
    @PostMapping("/admin/userface")
    public R updateAdminFace(MultipartFile file,Authentication authentication) {
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String s = UUID.randomUUID().toString();
        String fileName=s+suffix;
        File file1 = new File(baseUrl);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            file.transferTo(new File(baseUrl+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileName="http://localhost:"+serverPort+"/admin/download/"+fileName;
        Admin currentAdmin = AdminUtils.getCurrentAdmin();
        currentAdmin.setUserFace(fileName);
        adminService.updateById(currentAdmin);
        Admin admin = (Admin) authentication.getPrincipal();
        admin.setUserFace(fileName);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin, null, admin.getAuthorities()));
        return R.success("更新成功！");
    }

    @ApiOperation(value = "下载用户头像")
    @PostMapping("/admin/download/{name}")
    public R DownLoadAdminFace( @PathVariable("name") String name, HttpServletResponse response) {
        FileInputStream fileInputStream=null;
        ServletOutputStream outputStream=null;
        try {
            fileInputStream= new FileInputStream(new File(baseUrl + name));
             outputStream= response.getOutputStream();
            response.setContentType("image/jpeg");
           byte[] bytes=new byte[1024];
           Integer len;
           while ((len = fileInputStream.read(bytes)) != -1) {
               outputStream.write(bytes, 0, len);
               outputStream.flush();
           }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return R.success("更新用户头像成功！");

    }

}
